angular.module('baisonAutoPatch', ['baisonDb', 'baisonService'])
        //补丁包列表数据获取

        .factory('AutoPatchList', ['$rootScope', 'apiService', function ($rootScope, apiService) {
                return function () {
                    var param = {};
                    param['device'] = baison_app.api.deviceId;
                    param['shop_code'] = $rootScope.current_shop.ShopCode;
                    param['patch_status'] = 'TIP_INDEX_NOT_DOWNLOAD';
                    return apiService('patch/patch/get_list', param);
                };
            }])
        //补丁包下载
        .factory('AutoPatchDownload', ['$location', '$rootScope', '$q',  'dbTrans', '$http', 'timeStamp2String', 'apiService', function ($location, $rootScope, $q, dbTrans, $http, timeStamp2String, apiService) {
                //@TODO 下载路径IP地址需要从配置文件读取
                var configData = $api.getStorage('configData');
                var pathurl;
                if ((configData.api_url).indexOf(":", 10) == -1) {
                    pathurl = (configData.api_url).substring(0, (configData.api_url).indexOf("/", 10)) + "/patch/";
                } else if ((configData.api_url).indexOf("/", 30) != -1) {
                    pathurl = (configData.api_url).substring(0, (configData.api_url).indexOf("/", 30)) + "/manage/web/patch/";
                }

                var base_url = pathurl;
                var sys_type = '';//系统类型 pc 非pc
                try {
                    var os = nodeRequire('os');
                    switch (os.type()) {
                        case "Windows_NT":
                        case "Linux":
                        case "Darwin":
                            sys_type = 'pc';
                    }
                } catch (e) {
                    sys_type = '';
                }
                var install_deferred = {};
                var install_promise = {};
                 //下载包大小
                var install_size_deferred = $q.defer();
                var install_size_promise = install_size_deferred.promise;
                var patchtype = '';
                var patchcode = '';
                //获取下载地址
                var get_down_adress = function (patch) {
                    return patch.patch_url;
                };
                //删除管理器中的下载信息
                var del_manage_patch_info = function (patch, id, callback) {
                    baison_app.manager.query({
                        ids: [id]
                    }, function (ret, err) {
                        var data = ret.data;
                        if (data) {
                            baison_app.manager.remove({
                                ids: [id]
                            }, function (ret, err) {
                                var url = get_down_adress(patch);
                                baison_app.manager.enqueue({
                                    url: url,
                                    savePath: 'fs://' + patch.basename,
                                    cache: false,
                                    allowResume: false,
                                    title: patch.basename + $rootScope.language.TIPS_SET_SERVICE_PACK,
                                    uncompress: true,
                                    networkTypes: 'all',
                                    mimeType: 'application/zip',
                                }, function (ret, err) {
                                    if (ret.id) {
                                        patch_query_status({'patch': patch, 'id': ret.id}, callback);
                                    }
                                });
                            });
                        }
                    });
                };
                var patch_query_status = function (data, callback) {
                    baison_app.manager.query({
                        ids: [data.id]
                    }, function (ret, err) {
                        if (ret.data) {
                            if (ret.data[0].status == 4) { //下载发生错误
                                del_manage_patch_info(data.patch, data.id, callback);
                            } else {
                                callback(ret.data[0]);
                            }

                        }
                    });
                };
                //下载进度逻辑
                var patch_download_progress_logic = function (patch, callback) {
                    if (sys_type == 'pc') {
                        patch_download_progress_logic_pc(patch, callback);
                    } else {
                        patch_download_progress_logic_pad(patch, callback);
                    }
                };
                
                 //pc判断安装包的大小
                var is_check_patch_size = function(path,patch){
                     //console.log('请求的文件:',patch);
                     //console.log('网络请求文件大小:',patch.patch_size_bp);
                     var fs = nodeRequire('fs');
                     var install_size_deferred = $q.defer(1);
                     var install_size_promise = install_size_deferred.promise;
                     fs.stat(path, function(err, stats){
                        if(err){
                            install_size_deferred.resolve(0);
                        }else{
                            //console.log('本地下载的文件大小:',stats.size);
                            //console.log('大小相差:',patch.patch_size_bp - stats.size);
                            
                            //fixed：大小相差5万字节认为数据有问题 或者本地文件0字节
                            if(patch.patch_size_bp - stats.size > parseInt(stats.size * 0.1) || stats.size ==0){
                                install_size_deferred.resolve(0);
                            }else{
                                install_size_deferred.resolve(1);
                            }
                        }
                    });
                    return install_size_promise;
                };
                
                
                //PC端下载  TODO==================================
                //pc机补丁包下载逻辑
                
                 var pc_patch_download_logic = function (patch,callback) {
                    //console.log(patch);
                    var url = get_down_adress(patch);
                    var http = nodeRequire('http');
                    var fs = nodeRequire('fs');
                    var unzip = nodeRequire('unzip');
                    var path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.basename;
                    var dirpath = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.patch_code;
                    fs.exists(baison_app.api.fsDir + '\\' + 'download', function (exist) {
                        if (!exist) {
                            fs.mkdir(baison_app.api.fsDir + '\\' + 'download');
                        }
                    });
                    
                    http.get(url, function (res) {
                        if(res.statusCode==302 || res.statusCode==301){
                            http.get(res.headers.location,function(res300){
                               download_handler(res300);
                            });
                        }else if(res.statusCode==200){
                              download_handler(res);
                        }else{
                            console.log(res.statusCode);
                            console.log(patch);
                            var data = {};
                            data['patch_code'] = patch['patch_code'];
                            data['fd_ids'] = '';
                            data['patch_status'] = '未下载';
                            var prompt = '网络异常，下载数据包异常';
                            writeback_patchlog(data, prompt, '');
                            baison_app.api.toast({msg:'网络异常，'+patch.basename+'数据包下载失败'});
                            var ret = {};
                            ret.id = -1;
                            ret.totalSize = ret.finishSize = 1;
                            callback(ret);
                        }
                    });
                    
                    var download_handler = function(res){
                        var file = fs.createWriteStream(path);
                        res.pipe(file);
                        res.on('end', function () {
                            baison_app.fs.exist({
                                path: path
                            }, function (ret, err) {
                                if (ret.exist) {
                                   //console.log('下载的文件：',path);
                                   $rootScope.progressTips = '下载了文件:'+path;
                                   is_check_patch_size(path, patch).then(function(size){
                                       if(size == 0){
                                            //文件大小校验不通过
                                            var data = {};
                                            data['patch_code'] = patch['patch_code'];
                                            data['fd_ids'] = '';
                                            data['patch_status'] = '未下载';
                                            var prompt = '网络异常，下载数据包异常';//$rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                            writeback_patchlog(data, prompt, '');
                                            baison_app.api.toast({msg:'网络异常，'+patch.basename+'数据包下载失败'});
                                            var ret = {};
                                            ret.id = -1;
                                            ret.totalSize = ret.finishSize = 1;
                                            callback(ret);
                                            //console.log('100000000000000000000');
                                        }else if(size == 1){
                                            //文件大小一致
                                            var data = {};
                                            data['patch_code'] = patch['patch_code'];
                                            data['fd_ids'] = '';
                                            data['patch_status'] = 'TIP_INDEX_UNFIXED';
                                            var prompt = $rootScope.language.TIP_INDEX_DOWNLOAD_FINISHED_ONLY;
                                            writeback_patchlog(data, prompt, '');
                                            var ret = {};
                                            ret.id = 0;
                                            ret.totalSize = ret.finishSize = 1;
                                            //console.log('200000000000000000000');
                                            callback(ret);
                                        }
                                   });                                   
                                }else{
                                    setTimeout(function () {
                                       var ret = {};
                                       ret.id = 0;
                                       ret.totalSize = ret.finishSize = 1;
                                       //console.log('300000000000000000000');
                                       callback(ret);
                                    }, 1000);
                                }
                            });
                        	
                        });
                    }
                };
 
               //PC端下载逻辑 
                var patch_download_progress_logic_pc = function (patch, callback) {
                    pc_patch_download_logic(patch,callback);
                };

                //移动端下载逻辑
                var patch_download_progress_logic_pad = function (patch, callback) {
                    var url = get_down_adress(patch);
                    baison_app.manager.enqueue({
                        url: url,
                        savePath: 'fs://' + patch.basename,
                        cache: false,
                        allowResume: false,
                        title: patch.basename + $rootScope.language.TIPS_SET_SERVICE_PACK,
                        uncompress: true,
                        networkTypes: 'all',
                        mimeType: 'application/zip',
                    }, function (ret, err) {
                        if (ret.id) {
                            callback(ret);
                        }
                    });
                };


                //删除manage列表信息
                var del_manage_patchinfo = function (id) {
                    if (id != '') {
                        baison_app.manager.query({
                            ids: [id]
                        }, function (ret, err) {
                            var data = ret.data;
                            if (data) {
                                baison_app.manager.remove({
                                    ids: [id]
                                }, function (ret, err) {

                                });
                            }
                        });
                    }
                };

                //下载进度条
                var patch_download_progress = function (patch, callback) {
                    var patch_path = '';
                    if (sys_type != 'pc') {
                        patch_path = 'fs://' + patch.patch_code;
                    } else {
                        patch_path = baison_app.api.fsDir + '\\' + 'download' + '\\' + patch.basename;
                    }
                    //console.log(patch_path);
                    baison_app.fs.exist({
                        path: patch_path
                    }, function (ret, err) {
                        //console.log(ret);
                        if (!ret.exist) {
                            patch_download_progress_logic(patch, callback);
                        } else {
                            if(sys_type == 'pc'){
                                is_check_patch_size(patch_path,patch).then(function(size){
                                    if(size == 0){
                                         patch_download_progress_logic(patch, callback);
                                    }else if(size == 1){
                                        var ret = {};
                                        ret.id = 0;
                                        ret.totalSize = ret.finishSize = 1;
                                        callback(ret);
                                    }
                                });
                            }else{
                                ret = {};
                                ret.id = 0;
                                callback(ret);
                            } 
                        }
                    });
                };
                   //log
                var writeback_patchlog = function (data, prompt, index) {
                    var patchdata = {};
                    patchdata['patch_code'] = data['patch_code'];
                    patchdata['fd_ids'] = data['fd_ids'];
                    patchdata['patch_status'] = data['patch_status'];
                    patchdata['shop_code'] = $rootScope.current_shop.ShopCode;
                    patchdata['device'] = baison_app.api.deviceId;
                    patchdata['lastchanged'] = timeStamp2String(0, 'datetime');
                    patchdata['remark_log'] = patchdata['shop_code'] + ',' + patchdata['lastchanged'] + ',' + patchdata['patch_code'] + ',' + prompt;
                    apiService('patch/patch/add_patch_log', patchdata).then(function () {
                        $rootScope.patch_status = prompt;
                        if (index !== '') {
                            install_deferred[index].resolve('success');
                        }
                    });

                };
                //更新patch日志
                var update_patchlog = function (data, prompt) {
                    var patchdata = {};
                    patchdata['patch_status'] = data['status'];
                    patchdata['device'] = baison_app.api.deviceId;
                    patchdata['lastchanged'] = timeStamp2String(0, 'datetime');
                    patchdata['remark_log'] = patchdata['lastchanged'] + prompt;
                    apiService('patch/patch/update_patch_log', patchdata);
                };
                return {
                    "writeback_patchlog": writeback_patchlog,
                    "update_patchlog": update_patchlog,
                    "patch_download_progress": patch_download_progress,
                    "patch_query_status": patch_query_status
                };
            }
        ]);

       